package com.firebird.app.kotlin.stock.utils

import android.app.Activity
import android.app.AppOpsManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
//import android.support.annotation.RequiresApi
import android.text.TextUtils
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.RequiresApi
import com.firebird.app.kotlin.stock.utils.ToastUtil.showToast
import com.firebird.app.kotlin.stock.App
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*


object BaseUtils {
    //分割字符串
    fun spliteUtils(str: String, tag: String?): Array<String> {
        return str.split(tag!!).toTypedArray()
    }

    //截取后面字符串
    fun subBehindString(str: String, tag: String?): String {
        return str.substring(str.indexOf(tag!!) + 1)
    }

    //截取前面字符串
    fun subFrontString(str: String, tag: String?): String {
        return str.substring(0, str.indexOf(tag!!))
    }

    //截取后面几位
    fun subsubBehindNumString(str: String, num: Int): String {
        return str.substring(str.length - num)
    }

    //获取当前版本号
    fun getLocationCode(context: Context): Int {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            0
        }
    }

    //获取当前版本名字
    fun getLocationName(context: Context): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            ""
        }
    }

    //隐藏键盘
    fun hideInput(activity: Activity) {
        val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val v = activity.window.peekDecorView()
        if (null != v) {
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }

    fun showInput(editText: EditText) {
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                val inputManager = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager.showSoftInput(editText, 0)
            }
        },
                998)
    }

    fun getFource(editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
    }

    //保留两位小数并四舍五入
    fun formatDouble4(d: Double): String {
        val df = DecimalFormat("#.00")
        return df.format(d)
    }

    //检测通知是否打开
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    fun isNotificationEnable(context: Context): Boolean {
        val mAppOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        val appInfo = context.applicationInfo
        val pkg = context.applicationContext.packageName
        val uid = appInfo.uid
        var appOpsClass: Class<*>? = null /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager::class.java.name)
            val checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE, String::class.java)
            val opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION")
            val value = opPostNotificationValue[Int::class.java] as Int
            return checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) as Int == AppOpsManager.MODE_ALLOWED
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    }

    //替换字符串
    fun replaceString(s: String, bef: String?, aft: String?): String {
        return s.replace(bef, aft)
    }

    //复制文字
    fun copyMothod(context: Context, content: String?) {
        if (TextUtils.isEmpty(content)) {
            return
        }
        val myClipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = ClipData.newPlainText("content", content)
        myClipboard.primaryClip = clipData
        showToast(context, "复制成功")
    }

    //小数点后保留1位
    fun bit1(d: Double): String {
        if (d == 0.0) {
            return "0.0"
        }
        val decimalFormat = DecimalFormat("0.0")
        return decimalFormat.format(d)
    }

    fun toYuan(price: String): String {
        return if (TextUtils.isEmpty(price)) {
            ""
        } else {
            val aDouble = price.toDouble() / 100
            val decimalFormat = DecimalFormat("0.00")
            decimalFormat.format(aDouble)
        }
    }

    fun toFen(price: String): String {
        return if (TextUtils.isEmpty(price)) {
            ""
        } else {
            val aDouble = price.toDouble() * 100
            val nf: NumberFormat = DecimalFormat("#.#")
            val money = nf.format(aDouble)
            money + ""
        }
    }

    //保存图片
    fun saveBitmap(context: Context, bitmap: Bitmap): String {
        return try { // 获取内置SD卡路径
            val sdCardPath = Environment.getExternalStorageDirectory().path
            // 图片文件路径
            var file = File(sdCardPath)
            val files = file.listFiles()
            for (i in files.indices) {
                val file1 = files[i]
                val name = file1.name
                if (name.endsWith("twocode.jpg")) {
                    val flag = file1.delete()
                }
            }
            val filePath = "$sdCardPath/twocode.jpg"
            file = File(filePath)
            val os = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os)
            os.flush()
            os.close()
            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(context.contentResolver,
                    file.absolutePath, "twocode.jpg", null)
            //保存图片后发送广播通知更新数据库
            val uri = Uri.fromFile(file)
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            showToast(context, "图片保存成功")
            filePath
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
    }

    //把url转成bitmap
    fun returnBitMap(context: Context, url: String?) {
        Thread(Runnable {
            var imageurl: URL? = null
            try {
                imageurl = URL(url)
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            }
            try {
                val conn = imageurl!!.openConnection() as HttpURLConnection
                conn.doInput = true
                conn.connect()
                val `is` = conn.inputStream
                val bitmap = BitmapFactory.decodeStream(`is`)
                saveBitmap(context, bitmap)
                `is`.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }).start()
    }
}